package com.heima.behavior.service.impl;

import com.heima.behavior.pojo.ApLikesBehavior;
import com.heima.behavior.service.ApLikesBehaviorService;
import com.heima.model.behavior.dto.LikesBehaviorDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.entity.ApUser;
import com.heima.utils.common.threadUtil.ThreadLocalUtil;
import com.heima.utils.common.threadUtil.UserInfo;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Service
public class ApLikesBehaviorServiceImpl implements ApLikesBehaviorService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private MongoTemplate mongoTemplate;
    /**
     * 点赞
     * @param dto
     * @return
     */
    @Override
    public ResponseResult like(LikesBehaviorDto dto) {
        //1. 校验参数
        if (dto.getArticleId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        UserInfo userInfo = ThreadLocalUtil.get();
        if (userInfo == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        String like_hash_key="UESR_LIKES"+dto.getArticleId();
        Boolean hasKey = stringRedisTemplate.opsForHash().hasKey(like_hash_key, userInfo.getId().toString());
        //用户已经点赞
//        if(hasKey&&dto.getOperation()==0){
//            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
//        }
        //用户已经点赞 取消点赞
        if(hasKey&&dto.getOperation()==1){
            stringRedisTemplate.opsForHash().delete(like_hash_key,userInfo.getId().toString());
            //删除mongoDB数据库
            Query query = Query.query(Criteria.where("userId").is(userInfo.getId()).and("articleId").is(dto.getArticleId()));
            mongoTemplate.remove(query, ApLikesBehavior.class);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        //用户未点赞--点赞
        if(!hasKey&&dto.getOperation()==0){
            stringRedisTemplate.opsForHash().put(like_hash_key,userInfo.getId().toString(),"1");
            //保存关注数据到数据库
            ApLikesBehavior apLikesBehavior = new ApLikesBehavior();
            apLikesBehavior.setType(dto.getType());
            apLikesBehavior.setArticleId(dto.getArticleId());
            apLikesBehavior.setUserId(userInfo.getId().longValue());
            apLikesBehavior.setCreatedTime(new Date());

            mongoTemplate.insert(apLikesBehavior);

        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);


    }
}
